import React, { Component } from 'react';

const ShouldComponentUpdateDemo = () => {
  return (
    <div>
      <h4>第三条 shouldComponentUpdate</h4>
      <p>
        纯组件只能进行浅层比较，要进行深层比较，使用shouldComponentUpdate，用于编写自定义比较逻辑
        <br />
        返回true重新渲染组件，返回false阻止重新渲染
        <br />
        函数的第一个参数为nextProps，第二个参数为nextState
      </p>
      <Demo />
    </div>
  );
};

class Demo extends Component {
  constructor() {
    super();
    this.state = {
      person: {
        name: 'mike',
        age: 18,
        job: 'piaoke'
      }
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({ person: { ...this.state.person, job: 'chef' } });
    }, 1000);
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.person.name !== this.state.person.name || nextState.person.age !== this.state.person.age) {
      return true;
    }
    return false;
  }

  render() {
    console.log('render', '----');
    return (
      <div>
        {this.state.person.name} {this.state.person.age}
      </div>
    );
  }
}

export default ShouldComponentUpdateDemo;
